package com.vr.xuecheng.orders.config;

import com.alipay.api.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;

/**
 * @author hzh
 * @date 2025/04/05
 * 支付宝支付配置类
 */
@Log4j2
@Configuration
@ConfigurationProperties(prefix = "alipay")
public class AlipayClientConfig {
    @Resource
    private Environment environment;

    @Bean
    public AlipayClient alipayClient() {
        AlipayConfig alipayConfig = new AlipayConfig();
        // 支付宝网关
        alipayConfig.setServerUrl(environment.getProperty("alipay.gateway-url"));
        // 应用ID
        alipayConfig.setAppId(environment.getProperty("alipay.app-id"));
        // 应用私钥
        alipayConfig.setPrivateKey(environment.getProperty("alipay.merchant-private-key"));
        // 请求格式，固定格式json
        alipayConfig.setFormat(AlipayConstants.FORMAT_JSON);
        // 字符集，固定格式utf-8
        alipayConfig.setCharset(AlipayConstants.CHARSET_UTF8);
        // 支付宝公钥
        alipayConfig.setAlipayPublicKey(environment.getProperty("alipay.public-key"));
        // 签名类型
        alipayConfig.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
        // 创建客户端
        AlipayClient defaultAlipayClient;
        try {
            defaultAlipayClient = new DefaultAlipayClient(alipayConfig);
            return defaultAlipayClient;
        } catch (AlipayApiException e) {
            log.error("支付宝配置初始化失败");
            throw new RuntimeException(e.getMessage());
        }
    }
}
